package cn.juque.common.wx;

import cn.hutool.core.text.CharSequenceUtil;
import cn.juque.common.constants.WxConstants;
import cn.juque.common.constants.WxMessageEnum;
import cn.juque.common.exception.AppException;
import cn.juque.common.fastjson.abstracts.AbstractTypeReference;
import cn.juque.common.utils.HttpClientUtil;
import cn.juque.common.utils.dto.GetDTO;
import cn.juque.common.wx.dto.AccessTokenResponseDTO;
import cn.juque.common.wx.dto.WxLoginResponseDTO;
import org.springframework.beans.factory.annotation.Value;

/**
 * @author nuoka
 * @version 1.0.0
 * <li>IntelliJ IDEA</li>
 * <li>cn.juque.cn.juque.common.wx</li>
 * @date 2021/7/27 23:03
 **/
public class WxLoginHelper {

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.app_secret}")
    private String secret;

    /**
     * 微信小程序登录
     * @param code 登录码
     * @return WxLoginResponseDTO
     */
    public WxLoginResponseDTO login(String code) {
        String url = CharSequenceUtil.format(WxConstants.CODE_2_SESSION, appId, secret, code);

        WxLoginResponseDTO response = HttpClientUtil.get(new GetDTO(url, null, null),
            new AbstractTypeReference<WxLoginResponseDTO>() {});
        if ( null != response.getErrCode() && !WxMessageEnum.SUCCESS.getCode().equals(response.getErrCode())) {
            throw new AppException(String.valueOf(response.getErrCode()), response.getErrMsg());
        }
        return response;
    }

    /**
     * 获取access_token
     * @return AccessTokenResponseDTO
     */
    public AccessTokenResponseDTO getAccessToken() {
        String url = CharSequenceUtil.format(WxConstants.ACCESS_TOKEN, this.appId, this.secret);
        AccessTokenResponseDTO response = HttpClientUtil.get(new GetDTO(url, null, null),
            new AbstractTypeReference<AccessTokenResponseDTO>() {});
        if (!WxMessageEnum.SUCCESS.getCode().equals(response.getErrCode())) {
            throw new AppException(String.valueOf(response.getErrCode()), response.getErrMsg());
        }
        return response;
    }
}
